<?php
class CartController extends HomeController
{
    /** actionIndex =========================
     * @author   TuanNguyen
     * @desc     Show Index page cart
     *           Show list of product in cart
     *           and payment method
     * @param
     * @return
     * ============================================== */
    public function actionIndex()
    {
        $arr_cart = Yii::app()->session["cart"];

        if ( !is_array($arr_cart) )
        {
            $arr_cart = array();
        }

        $this->render("index", array("ss_cart" => $arr_cart));
    }

    /** actionAdd =========================
     * @author   TuanNguyen
     * @desc     Add product to cart session
     *           if exist product, update amount of this
     * @param
     * @return
     * ============================================== */
    public function actionAdd()
    {
        if ( isset(Yii::app()->session["cart"]) )
        {
            $arr_cart = Yii::app()->session["cart"];
        }
        else
        {
            $arr_cart = array();
        }

        $i_itemKey    = $_REQUEST["item_key"];
        $i_itemAmount = $_REQUEST["txt_amount"];

        if ( isset($arr_cart[$i_itemKey]) && $arr_cart[$i_itemKey]["amount"] > 50 )
        {
            $o_error          = new ErrorEntity();
            $o_error->errCode = "ERR_5";
            $o_error->param   = null;
            $s_errorMsg       = self::getErrorMessage($o_error);

            $arr_result = array("error" => $s_errorMsg );
            echo json_encode($arr_result);
            Yii::app()->end();
        }

        #region Update amount of existed product in cart
        if ( isset($arr_cart[$i_itemKey]) )
        {
            $arr_cart[$i_itemKey]["amount"] = $arr_cart[$i_itemKey]["amount"] + $i_itemAmount;
        }
        #End Region

        #region Insert amount of existed product in cart
        if ( !isset($arr_cart[$i_itemKey]) )
        {
            $o_product = Product::model()->findByPk($i_itemKey);
            if( !($o_product instanceof Product) ) 
            {
                $o_error          = new ErrorEntity();
                $o_error->errCode = "ERR_5";
                $o_error->param   = null;
                $s_errorMsg       = self::getErrorMessage($o_error);

                $arr_result = array("error" => $s_errorMsg );
                echo json_encode($arr_result);
                Yii::app()->end();
            }

            $arr_cart[$i_itemKey]["key"]     = $o_product->identification;
            $arr_cart[$i_itemKey]["subject"] = $o_product->subject;
            $arr_cart[$i_itemKey]["price"]   = $o_product->price;
            $arr_cart[$i_itemKey]["amount"]  = $i_itemAmount;
        }
        #End Region

        Yii::app()->session["cart"] = $arr_cart;

        $arr_result = array("result" => count($arr_cart) );
        echo json_encode($arr_result);
        Yii::app()->end();
    }//End actionIndex


    /** actionDeleteCart =========================
     * @author   TuanNguyen
     * @desc     Delete cart session
     * 
     * @param
     * @return
     * ============================================== */
    public function actionDeleteCart()
    {
        //Init
        $bool_result  = false;
        $arr_errorMsg = null;
        
        #region remove cart session if exist
        if ( isset(Yii::app()->session["cart"]) )
        {
            unset(Yii::app()->session["cart"]);
            $bool_result = true;
        }
        #End Region

        if ( $bool_result == false )
        {
            $o_error          = new ErrorEntity();
            $o_error->errCode = "ERR_7";
            $o_error->param   = null;
            $arr_errorMsg     = self::getErrorMessage($o_error);
        }

        #region set param to view
        $arr_result = array (
            "result" => $bool_result,
            "error"  => $arr_errorMsg
        );
        echo json_encode($arr_result);
        Yii::app()->end();
        #End Region
    }//End actionDeleteCart


    /** actionDelete =========================
     * @author   TuanNguyen
     * @desc     Delete item in cart session
     *
     * @param
     * @return
     * ============================================== */
    public function actionDelete()
    {
        //Init
        $bool_result = false;
        $s_errorMsg  = null;

        #region Check request param
        if( !isset($_REQUEST["item_key"]) )
        {
            $o_error          = new ErrorEntity();
            $o_error->errCode = "ERR_3";
            $o_error->param   = null;
            $s_errorMsg       = self::getErrorMessage($o_error);

            $arr_result = array( 
                "result" => $bool_result,
                "error"  => $s_errorMsg
            );
            echo json_encode($arr_result);
            Yii::app()->end();
        }
        #End Region

        //Init
        $i_key = $_REQUEST["item_key"];

        #region remove cart session if exist
        if ( isset(Yii::app()->session["cart"][$i_key]) )
        {
            $arr_cart = Yii::app()->session["cart"];
            unset($arr_cart[$i_key]);
            Yii::app()->session["cart"] = $arr_cart;
            $bool_result = true;
        }
        else
        {
            $o_error          = new ErrorEntity();
            $o_error->errCode = "ERR_8";
            $o_error->param   = null;
            $s_errorMsg       = self::getErrorMessage($o_error);
        }
        #End Region

        #region set param to view
        $arr_result = array( "result" => $bool_result,
                             "error"  => $s_errorMsg
                            );
        echo json_encode($arr_result);
        Yii::app()->end();
        #End Region
    }//End actionDelete


    /** actionUpdate =========================
     * @author   TuanNguyen
     * @desc     Update item in cart session
     *
     * @param
     * @return
     * ============================================== */
    public function actionUpdate()
    {
        //Init
        $dou_result  = null;
        $s_errorMsg  = null;
        $i_key       = $_REQUEST["item_key"];
        $i_amount    = $_REQUEST["txt_quantity"];

        #region update item in cart session if exist
        if ( isset(Yii::app()->session["cart"][$i_key]) )
        {
            $arr_cart = Yii::app()->session["cart"];
            $arr_cart[$i_key]["amount"] = $i_amount;
            Yii::app()->session["cart"] = $arr_cart;
            $dou_result = $arr_cart[$i_key]["amount"]*$arr_cart[$i_key]["price"];
        }
        else
        {
            $o_error          = new ErrorEntity();
            $o_error->errCode = "ERR_8";
            $o_error->param   = null;
            $s_errorMsg       = self::getErrorMessage($o_error);
        }
        #End Region

        #region set param to view
        $arr_result = array(
            "result" => $dou_result,
            "error"  => $s_errorMsg
        );
        echo json_encode($arr_result);
        Yii::app()->end();
        #End Region
    }


    /** actionCheckout =========================
     * @author   TuanNguyen
     * @desc     Update item in cart session
     *
     * @param
     * @return
     * ============================================== */
    public function actionCheckout()
    {
        //init
        $s_errorMsg = null;
        $arr_cart   = Yii::app()->session["cart"];
        $o_account  = null;

        #region set param to view
        if ( !is_array($arr_cart) || count($arr_cart) <= 0 )
        {
            $s_url = Yii::app()->createUrl( "product/index");
            $this->redirect($s_url);
        }

        $this->render(
            "checkout",
            array(
                "s_errorMsg" => $s_errorMsg,
                "o_account"  => $o_account
            )
        );//End render
        #End Region
    }//End actionCheckout


    /** actionOrder =========================
     * @author   TuanNguyen
     * @desc     Commit 1 order by payment method
     *
     * @param
     * @return
     * ============================================== */
    public function actionOrder()
    {
        $i_currentPayMethod = $_REQUEST["hidd_payMethod"];
        $arr_cart           = Yii::app()->session["cart"];
        $o_buyerInfo        = new Order();
        $bool_result        = false;
        $s_errorMsg         = null;
        $s_resultMsg        = null;

        $o_buyerInfo->name          = $_REQUEST["txt_name"];
        $o_buyerInfo->phone         = $_REQUEST["txt_phone"];
        $o_buyerInfo->address       = $_REQUEST["ta_address"];
        $o_buyerInfo->delivery_date = $_REQUEST["txt_deliveryDate"];
        $o_buyerInfo->information   = $_REQUEST["ta_information"];

        switch ($i_currentPayMethod)
        {
            case Order::PAYMETHOD_CASH://Cash
                $bool_result = self::orderByCash($o_buyerInfo, $arr_cart);
                break;

            default:
                break;
        }//End switch

        #region set finishing order mesage
        if ( $bool_result instanceof ErrorEntity )
        {
            $s_errorMsg = self::getErrorMessage($bool_result);
        }
        elseif ( $bool_result == true ) 
        {
            Yii::app()->session->destroy();

            $o_error          = new ErrorEntity();
            $o_error->errCode = "NOT_1";
            $o_error->param   = null;
            $s_resultMsg      = self::getErrorMessage($o_error);
        }
        else
        {
            $o_error          = new ErrorEntity();
            $o_error->errCode = "ERR_1";
            $o_error->param   = null;
            $s_errorMsg       = self::getErrorMessage($o_error);
        }
        #End Region

        #region set param to view
        $arr_result = array(
            "result"    => $bool_result,
            "resultMsg" => $s_resultMsg,
            "errorMsg"  => $s_errorMsg
        );
        echo json_encode($arr_result);
        Yii::app()->end();
        #End Region
    }//End actionOrder


    /** orderByCash =========================
     * @author   TuanNguyen
     * @desc     Commit 1 order by cash method
     *
     * @param Order $o_BuyerInfo
     * @return boolean
     * ============================================== */
    private function orderByCash(Order $o_order, $arr_cart)
    {
        $d_totalPrice           = 0;
        $i_totalAmount          = 0;
        $date_insert            = new DateTime();
        $s_orderDetailStatement = null;

        #region Calculate total price, amount for order, build SQL for order detail
        foreach ($arr_cart as $key=>$arr_product)
        {
            $i_totalAmount += $arr_product["amount"];
            $d_totalPrice  += $arr_product["price"] * $arr_product["amount"];

            $s_orderDetailStatement .= "(
                orderKey,
                '".$arr_product["key"]."',
                '".$arr_product["amount"]."',
                '".$arr_product["price"]."',
                NULL,
                '".$date_insert->format("Y-m-d H:i:s")."'
            ),";
        }//End foreach

        $o_order->total_amount = $i_totalAmount;
        $o_order->total_price  = $d_totalPrice;

        //Remove last comma in statement
        $s_orderDetailStatement = substr($s_orderDetailStatement, 0, -1);
        #End Region

        #region add order and information to database
        $b_result = Order::addDataToDb($o_order, $s_orderDetailStatement);
        #End Region

        return $b_result;
    }


    /** getErrorMessage =============================
     * @author   TuanNguyen
     * @desc     get error message from array of error entity
     *           set reference parameter if there are an error
     * @param    $errorEnts: array of error entity or error entity
     * @return   string: error message
     * ============================================== */
    private function getErrorMessage($errorEnts)
    {
        $arr_errorMessage = array(
            "ERR_1" => "There are an error with parameters in SQL statement. ",
            "ERR_2" => "SQLException",
            "ERR_3" => "Recieved Parameter is wrong or missing. ",
            "ERR_4" => "format of fieldName is formatName, please type value as formatName format . ",
            "ERR_5" => "Data is updating...",
            "ERR_6" => "Không tìm thấy kết quả phù hợp.",
            "ERR_7" => "Bạn không có giỏ hàng để hủy.",
            "ERR_8" => "Giỏ hàng không tồn tại mặt hàng muốn xóa.",
            "NOT_1" => "Bạn đã đặt hàng thành công, chúng tôi sẽ liên lạc với bạn trong vòng 1 ngày, xin cảm ơn!."
        );
    
        //Return error message
        if ( is_array($errorEnts) )
        {
            return ErrorEntity::setErrorMessageByArray($errorEnts, $arr_errorMessage);
        }
        elseif ( $errorEnts instanceof ErrorEntity )
        {
            return ErrorEntity::setErrorMessageByEntity($errorEnts, $arr_errorMessage);
        }
    }
}